#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <fstream>
#include <sstream>
#include <memory>
#include <filesystem> //C++17
#include <unistd.h>
#include <time.h>
#include "Mutex.hpp"
// + 日志的可变部分(<< "hello world"

namespace LogModule
{
       using namespace Lock;
    std::string CurrentTime()
    {
        time_t time_stamp=::time(nullptr);
        struct tm curr;
        localtime_r(&time_stamp, &curr);
        char buffer[1024];

        snprintf(buffer,sizeof(buffer),"%4d-%02d-%02d %02d:%02d:%02d",
        curr.tm_year + 1900,
                 curr.tm_mon + 1,
                 curr.tm_mday,
                 curr.tm_hour,
                 curr.tm_min,
                 curr.tm_sec);
    return buffer;

    }
    enum class LogLevel
    {
        DEBUG=1,
        INFO,
        WARNING,
        ERROR,
        FATAL

    };
    
    std::string Level2String(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "None";
        }
    }
    class LogStrategy
    {
        public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string & message) = 0 ;
    };

    class ControlStrategy : public LogStrategy
    {
        public:
        ControlStrategy()
        {
            
        }
        ~ControlStrategy()
        {

        }
        void SyncLog(const std::string& message)
        {
            LockGuard lockguard(_mut);
            std::cout<<message<<std::endl;
        }

        private:
        Mutex _mut;
        
    };
   
    /*std::filesystem::exists(_logpath)*/
    const std::string defaultlogpath = "./log/";
    const std::string defaultlogname = "log.txt";
    class FileStrategy : public LogStrategy
    {
        public:
        FileStrategy(const std::string& logpath=defaultlogpath,const std::string& logname = defaultlogname)
        :_logpath(logpath)
        ,_logname(logname)
        {
            LockGuard lockguard(_mut);
            if(std::filesystem::exists(_logpath))
            {
                return;    
            }
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch(std::filesystem::filesystem_error& t)
            {
                std::cerr<<t.what()<<std::endl;
            }
        }
        ~FileStrategy()
        {

        }
        void SyncLog(const std::string& message)
        {
           LockGuard lockgurad(_mut);
           std::string log = _logpath+_logname;
           std::ofstream out(log,std::ios::app);
           if(!out.is_open())
           {
                std::cout<<"打开失败"<<std::endl;
                return;
           }
           out<<message<<"\n";
           out.close();
        }
        
        private:
        Mutex _mut;

        std::string _logpath;
        std::string _logname;
    };
    class Logger
    {
        public:
        Logger()
        {
            _strategy=std::make_shared<ControlStrategy>(); 
        }
        void EnableControl()
        {
             _strategy=std::make_shared<ControlStrategy>(); 
        }
        void EnableFile()
        {
            _strategy=std::make_shared<FileStrategy>();
        }
        ~Logger()
        {

        }
        //一条完整的信息: [2024-08-04 12:27:03] [DEBUG] [202938] [main.cc] [16]
        class LogMessage
        {
            public:
            LogMessage(LogLevel level,const std::string &filename, int line,Logger& logger)
            :_time(CurrentTime())
            ,_level(level)
            ,_pid(::getpid())
            ,_name(filename)
            ,_line(line)
            ,_logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer << "[" << _time << "] "
                         << "[" <<Level2String(_level) << "] "
                         << "[" << _pid << "] "
                         << "[" << _name << "] "
                         << "[" << _line << "] - ";
              _loginfo = ssbuffer.str();
              //std::cout<<_loginfo<<std::endl;         
            }
            template<class T>
            LogMessage &operator<<(const T& info)
            {
                std::stringstream ss;
                ss<<info;
                _loginfo += ss.str();
                return *this;
            }
            ~LogMessage()
            {
                if(_logger._strategy)
                {
                    
                    _logger._strategy->SyncLog(_loginfo);
                }
                
            }

            private:
            std::string _time;
            LogLevel _level;;
            pid_t _pid;
            std::string _name;
            int _line;
            std::string _loginfo;
            Logger &_logger;
        };
        LogMessage operator()(LogLevel level, const std::string &filename, int line)
        {
            return LogMessage(level, filename, line,*this);
        }
        private:
        std::shared_ptr<LogStrategy> _strategy;
    };

    Logger logger;
#define LOG(level) logger(level,__FILE__,__LINE__)
#define ENABLE_CONSOLE_LOG() logger.EnableControl()
#define ENABLE_FILE_LOG() logger.EnableFile()

}